package com.uduew.sjd.ui.form

import android.os.Bundle
import android.util.Base64
import android.view.KeyEvent
import com.uduew.sjd.api.LiveDetectionApi
import com.uduew.sjd.api.LiveDetectionApi.ResLiveDetectionBean
import com.uduew.sjd.bean.HttpBean
import com.uduew.sjd.config.AppConfig
import com.uduew.sjd.message.Messages
import com.uduew.sjd.message.PageMessenger
import com.uduew.sjd.net.DataRepository
import com.uduew.sjd.net.DataResult
import com.uduew.sjd.ui.base.BaseActivity
import com.uduew.sjd.ui.base.StateHolder
import com.uduew.sjd.utils.ToastUtils
import com.hjq.bar.OnTitleBarListener
import com.hjq.bar.TitleBar
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.kongzue.dialogx.dialogs.TipDialog
import com.kongzue.dialogx.dialogs.WaitDialog
import com.kunminx.architecture.ui.page.DataBindingConfig
import com.kunminx.architecture.ui.state.State
import com.otaliastudios.cameraview.CameraListener
import com.otaliastudios.cameraview.PictureResult
import com.uduew.sjd.BR
import com.uduew.sjd.R
import com.uduew.sjd.databinding.ActivityLiveBinding
import java.io.File
import java.io.FileInputStream

class LiveActivity : BaseActivity() {

    private lateinit var mStates: LiveActivityStates
    private lateinit var mMessenger: PageMessenger

    override fun initViewModel() {
        mStates = getActivityScopeViewModel(LiveActivityStates::class.java)
        mMessenger = getApplicationScopeViewModel(PageMessenger::class.java)
    }

    private lateinit var binding: ActivityLiveBinding


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        XXPermissions.with(this)
            .permission(
                Permission.CAMERA
            )
            .request(object : OnPermissionCallback {
                override fun onGranted(
                    permissions: List<String?>,
                    allGranted: Boolean
                ) {
                    if (!allGranted) {
                        TipDialog.show(getString(R.string.camera_permissions_are_required))
                        return
                    }
                    binding = (getBinding() as ActivityLiveBinding).apply {
                        camera.setLifecycleOwner(this@LiveActivity)
                        camera.open()
                    }
                }
            })
    }


    override fun getDataBindingConfig(): DataBindingConfig? {
        return DataBindingConfig(R.layout.activity_live, BR.vm, mStates).addBindingParam(
            BR.click,
            ClickProxy()
        ).addBindingParam(BR.titleBarListener, TitleBarListener())
            .addBindingParam(BR.cameraListener, CameraHandlerListener())
    }

    class LiveActivityStates : StateHolder() {
        var liveState: State<String> = State("2") // 1默认状态 2识别准备状态 3识别完成 4开始拍照

    }

    open inner class ClickProxy {
        fun live() {
            if (mStates.liveState.get() == "3") {
                mMessenger.input(Messages(Messages.EVENT_CERTIFICATION_SUCCESS))
                finish()
                return
            }
            if (mStates.liveState.get() == "1") {
                mStates.liveState.set("2")
                return
            }
            if (mStates.liveState.get() == "2") {
                mStates.liveState.set("4")
                return
            }
            mStates.liveState.set("2")
        }
    }

    inner class CameraHandlerListener : CameraListener() {
        override fun onPictureTaken(result: PictureResult) {
            super.onPictureTaken(result)
            val storageDir = filesDir
            val file = File(storageDir, "photo_${System.currentTimeMillis()}.jpg")
            result.toFile(file) { file ->
                if (file != null) {
                    var base64 = fileToBase64(file.absoluteFile.toString())
                    if (base64.isEmpty()) {
                        ToastUtils.showShortToast("base64fail")
                    } else {
                        var arrayList = ArrayList<String>()
                        arrayList.add(base64)
                        var bean = LiveDetectionApi.ReqLiveDetectionBean(
                            base64,
                            "frisbee",
                            arrayList
                        )
                        WaitDialog.show(getString(R.string.Identification_in_progress))
                        DataRepository.getInstance()
                            .liveDetection(
                                this@LiveActivity,
                                LiveDetectionApi(bean)
                            ) { result: DataResult<HttpBean<ResLiveDetectionBean>> ->
                                WaitDialog.dismiss()
                                if (!result.responseStatus.isSuccess) {
                                    TipDialog.show(getString(R.string.authentication_failed) + result.responseStatus.responseCode)
                                    mStates.liveState.set("1")
                                    return@liveDetection
                                }
                                result.result.data?.let {
                                    if (it.isLaboured) {
                                        mStates.liveState.set("3")
                                    }
                                }
                            }
                    }
                }
            }
        }
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (mStates.liveState.get() == "3") {
                mMessenger.input(Messages(Messages.EVENT_CERTIFICATION_SUCCESS))
                finish()
                return true
            }
        }
        return super.onKeyDown(keyCode, event)
    }


    inner class TitleBarListener : OnTitleBarListener {
        override fun onLeftClick(titleBar: TitleBar?) {
            super.onLeftClick(titleBar)
            if (mStates.liveState.get() == "3") {
                mMessenger.input(Messages(Messages.EVENT_CERTIFICATION_SUCCESS))
            }
            finish()
        }

        override fun onRightClick(titleBar: TitleBar?) {
            super.onRightClick(titleBar)
        }
    }

    fun fileToBase64(filePath: String): String {
        val file = File(filePath)
        var inputStream: FileInputStream? = null
        try {
            inputStream = FileInputStream(file)
            val buffer = ByteArray(file.length().toInt())
            inputStream.read(buffer)
            return Base64.encodeToString(buffer, Base64.NO_WRAP)
        } catch (e: Exception) {
            e.printStackTrace()
            return ""
        } finally {
            inputStream?.close()
        }
    }

}